import click
from urllib.parse import quote_plus
from sqlalchemy import create_engine,Connection
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy import MetaData
from flask import Flask, current_app, g

def get_db()-> Connection:
    if 'db' not in g:
        try:
          config=current_app.config['CONFIG']['mysql_config']
          username=config['user']
          password=config['password']
          # 对密码进行URL编码
          quoted_password = quote_plus(password)
          localhost=config['host']
          port=config['port']
          databasename=config['database']
          engine = create_engine(f'mysql+pymysql://{username}:{quoted_password}@{localhost}:{port}/{databasename}')
          g.db=engine
          return g.db
        except Exception as e:
          current_app.logger.error(f"数据库连接失败: {e}")
        return None
    return g.db

def init_db():
    engine = get_db()

    metadata_obj = MetaData()

    user = Table(
    "user",
    metadata_obj,
    Column("uid", Integer, primary_key=True),
    Column("name", String(255)),
    Column("gender", String(255)),
    )

    metadata_obj.create_all(engine)


@click.command('init-db')
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database.')

def init_app(app:Flask):
    app.cli.add_command(init_db_command)